<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/attendance_manager.php';
require_once '../includes/user.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和考勤管理器
$database = getDatabaseConnection();
$attendanceManager = new AttendanceManager($database);

// 获取调试信息
$debugInfo = [];
if (isset($_POST['debug_import'])) {
    if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] === UPLOAD_ERR_OK) {
        $filePath = $_FILES['import_file']['tmp_name'];
        
        // 模拟导入过程，但不实际插入数据
        $debugInfo = debugCSVImport($attendanceManager, $filePath);
    } else {
        $debugInfo['error'] = '请选择要调试的文件';
    }
}

/**
 * 调试CSV导入过程
 */
function debugCSVImport($attendanceManager, $filePath) {
    $debugInfo = [];
    $debugInfo['file_info'] = [
        'path' => $filePath,
        'exists' => file_exists($filePath),
        'size' => filesize($filePath),
        'extension' => pathinfo($filePath, PATHINFO_EXTENSION)
    ];
    
    if (!file_exists($filePath)) {
        $debugInfo['error'] = '文件不存在';
        return $debugInfo;
    }
    
    if (($handle = fopen($filePath, 'r')) !== FALSE) {
        $row = 0;
        $debugInfo['rows'] = [];
        
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            $row++;
            $rowInfo = [
                'row_number' => $row,
                'data' => $data,
                'column_count' => count($data),
                'parsed_data' => [],
                'validation' => [],
                'user_info' => [],
                'record_check' => []
            ];
            
            // 解析数据
            if ($row === 1) {
                $rowInfo['type'] = 'header';
                $rowInfo['parsed_data'] = [
                    'username' => '标题行',
                    'record_date' => '标题行',
                    'status' => '标题行'
                ];
            } else {
                $rowInfo['type'] = 'data';
                
                // 解析数据
                $username = trim($data[0]);
                $recordDate = trim($data[1]);
                $status = trim($data[2]);
                $morningClockIn = isset($data[3]) ? trim($data[3]) : null;
                $morningClockOut = isset($data[4]) ? trim($data[4]) : null;
                $afternoonClockIn = isset($data[5]) ? trim($data[5]) : null;
                $afternoonClockOut = isset($data[6]) ? trim($data[6]) : null;
                $allDayWorkHours = isset($data[7]) ? floatval($data[7]) : null;
                $notes = isset($data[8]) ? trim($data[8]) : null;
                
                $rowInfo['parsed_data'] = [
                    'username' => $username,
                    'record_date' => $recordDate,
                    'status' => $status,
                    'morning_clock_in' => $morningClockIn,
                    'morning_clock_out' => $morningClockOut,
                    'afternoon_clock_in' => $afternoonClockIn,
                    'afternoon_clock_out' => $afternoonClockOut,
                    'all_day_work_hours' => $allDayWorkHours,
                    'notes' => $notes
                ];
                
                // 验证数据
                $validationErrors = [];
                
                if (empty($username)) {
                    $validationErrors[] = '用户名为空';
                }
                if (empty($recordDate)) {
                    $validationErrors[] = '日期为空';
                }
                if (empty($status)) {
                    $validationErrors[] = '状态为空';
                }
                
                if (!empty($recordDate) && !preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $recordDate)) {
                    $validationErrors[] = '日期格式错误，应为 YYYY-MM-DD 或 YYYY-M-D';
                }
                
                $rowInfo['validation']['errors'] = $validationErrors;
                $rowInfo['validation']['is_valid'] = empty($validationErrors);
                
                // 获取用户信息
                if (!empty($username)) {
                    $userId = $attendanceManager->getUserIdByUsername($username);
                    $rowInfo['user_info'] = [
                        'username' => $username,
                        'user_id' => $userId,
                        'user_exists' => !empty($userId)
                    ];
                    
                    // 检查记录是否已存在
                    if ($userId && !empty($recordDate)) {
                        $recordExists = $attendanceManager->recordExists($userId, $recordDate);
                        $rowInfo['record_check'] = [
                            'user_id' => $userId,
                            'record_date' => $recordDate,
                            'record_exists' => $recordExists
                        ];
                    }
                }
            }
            
            $debugInfo['rows'][] = $rowInfo;
        }
        
        fclose($handle);
    } else {
        $debugInfo['error'] = '无法打开文件';
    }
    
    return $debugInfo;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV导入调试 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .debug-section {
            margin-bottom: 2rem;
        }
        .row-info {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
            padding: 1rem;
        }
        .row-header {
            background-color: #f8f9fa;
            padding: 0.5rem;
            border-radius: 0.375rem;
            margin-bottom: 0.5rem;
        }
        .validation-error {
            color: #dc3545;
            font-weight: bold;
        }
        .validation-success {
            color: #198754;
            font-weight: bold;
        }
        .data-table {
            font-size: 0.875rem;
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-bug me-2"></i>CSV导入调试
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-file-csv me-2"></i>CSV导入调试工具
                            </h5>
                        </div>
                        <div class="card-body">
                            <!-- 文件上传表单 -->
                            <form method="post" enctype="multipart/form-data" class="mb-4">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="mb-3">
                                            <label class="form-label">选择CSV文件</label>
                                            <input type="file" name="import_file" class="form-control" accept=".csv" required>
                                            <div class="form-text">选择要调试的CSV文件，系统会分析文件内容但不实际导入数据</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 d-flex align-items-end">
                                        <button type="submit" name="debug_import" class="btn btn-primary w-100">
                                            <i class="fas fa-search me-2"></i>分析文件
                                        </button>
                                    </div>
                                </div>
                            </form>

                            <?php if (!empty($debugInfo)): ?>
                                <!-- 文件信息 -->
                                <div class="debug-section">
                                    <h6><i class="fas fa-info-circle me-2"></i>文件信息</h6>
                                    <div class="table-responsive">
                                        <table class="table table-bordered data-table">
                                            <tbody>
                                                <tr>
                                                    <th width="200">文件路径</th>
                                                    <td><?php echo htmlspecialchars($debugInfo['file_info']['path']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>文件存在</th>
                                                    <td>
                                                        <span class="badge <?php echo $debugInfo['file_info']['exists'] ? 'bg-success' : 'bg-danger'; ?>">
                                                            <?php echo $debugInfo['file_info']['exists'] ? '是' : '否'; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>文件大小</th>
                                                    <td><?php echo number_format($debugInfo['file_info']['size']); ?> 字节</td>
                                                </tr>
                                                <tr>
                                                    <th>文件扩展名</th>
                                                    <td><?php echo htmlspecialchars($debugInfo['file_info']['extension']); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                <?php if (isset($debugInfo['error'])): ?>
                                    <div class="alert alert-danger">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <?php echo htmlspecialchars($debugInfo['error']); ?>
                                    </div>
                                <?php endif; ?>

                                <?php if (isset($debugInfo['rows'])): ?>
                                    <!-- 数据行分析 -->
                                    <div class="debug-section">
                                        <h6><i class="fas fa-table me-2"></i>数据行分析 (共 <?php echo count($debugInfo['rows']); ?> 行)</h6>
                                        
                                        <?php foreach ($debugInfo['rows'] as $rowInfo): ?>
                                            <div class="row-info">
                                                <div class="row-header">
                                                    <strong>第 <?php echo $rowInfo['row_number']; ?> 行</strong>
                                                    <span class="badge <?php echo $rowInfo['type'] === 'header' ? 'bg-info' : 'bg-primary'; ?> ms-2">
                                                        <?php echo $rowInfo['type'] === 'header' ? '标题行' : '数据行'; ?>
                                                    </span>
                                                </div>
                                                
                                                <!-- 原始数据 -->
                                                <div class="mb-2">
                                                    <strong>原始数据:</strong>
                                                    <code><?php echo implode(' | ', array_map('htmlspecialchars', $rowInfo['data'])); ?></code>
                                                    <span class="badge bg-secondary ms-2"><?php echo $rowInfo['column_count']; ?> 列</span>
                                                </div>
                                                
                                                <?php if ($rowInfo['type'] === 'data'): ?>
                                                    <!-- 解析后的数据 -->
                                                    <div class="mb-2">
                                                        <strong>解析数据:</strong>
                                                        <div class="table-responsive">
                                                            <table class="table table-sm table-bordered data-table">
                                                                <thead>
                                                                    <tr>
                                                                        <th>用户名</th>
                                                                        <th>日期</th>
                                                                        <th>状态</th>
                                                                        <th>上午上班</th>
                                                                        <th>上午下班</th>
                                                                        <th>下午上班</th>
                                                                        <th>下午下班</th>
                                                                        <th>全天工时</th>
                                                                        <th>备注</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <tr>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['username']); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['record_date']); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['status']); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['morning_clock_in'] ?? '-'); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['morning_clock_out'] ?? '-'); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['afternoon_clock_in'] ?? '-'); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['afternoon_clock_out'] ?? '-'); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['all_day_work_hours'] ?? '-'); ?></td>
                                                                        <td><?php echo htmlspecialchars($rowInfo['parsed_data']['notes'] ?? '-'); ?></td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- 验证结果 -->
                                                    <div class="mb-2">
                                                        <strong>数据验证:</strong>
                                                        <?php if ($rowInfo['validation']['is_valid']): ?>
                                                            <span class="validation-success">✓ 数据格式正确</span>
                                                        <?php else: ?>
                                                            <div class="validation-error">
                                                                ✗ 验证错误:
                                                                <ul class="mb-0">
                                                                    <?php foreach ($rowInfo['validation']['errors'] as $error): ?>
                                                                        <li><?php echo htmlspecialchars($error); ?></li>
                                                                    <?php endforeach; ?>
                                                                </ul>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- 用户信息 -->
                                                    <?php if (!empty($rowInfo['user_info'])): ?>
                                                        <div class="mb-2">
                                                            <strong>用户信息:</strong>
                                                            <?php if ($rowInfo['user_info']['user_exists']): ?>
                                                                <span class="validation-success">
                                                                    ✓ 用户存在 (ID: <?php echo $rowInfo['user_info']['user_id']; ?>)
                                                                </span>
                                                            <?php else: ?>
                                                                <span class="validation-error">
                                                                    ✗ 用户不存在: <?php echo htmlspecialchars($rowInfo['user_info']['username']); ?>
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <!-- 记录检查 -->
                                                    <?php if (!empty($rowInfo['record_check'])): ?>
                                                        <div class="mb-2">
                                                            <strong>记录检查:</strong>
                                                            <?php if ($rowInfo['record_check']['record_exists']): ?>
                                                                <span class="validation-error">
                                                                    ✗ 记录已存在 (用户ID: <?php echo $rowInfo['record_check']['user_id']; ?>, 日期: <?php echo $rowInfo['record_check']['record_date']; ?>)
                                                                </span>
                                                            <?php else: ?>
                                                                <span class="validation-success">
                                                                    ✓ 记录不存在，可以导入
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-file-csv fa-4x mb-3"></i>
                                    <h4>上传CSV文件进行调试</h4>
                                    <p>选择CSV文件后，系统会分析文件内容并显示详细的调试信息</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
